package com.kjhxtc.restfulrunner;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @author 杜神
 * @version 1.0
 * @since 2022/3/16 13:34
 */
public class ResultCollector {

    private final List<Result> results = new LinkedList<>();

    public void add(Result result) {
        if (result != null) {
            Log.debug("{}|cost:{}|success:{}|status:{} {}", results.size(), result.getCost(), result.isSuccess(), result.getStatusCode(),result.getErrMsg());
            results.add(result);
        }
    }

    public double qps(long costMill) {
        long costSecond = costMill / 1000;
        if (costSecond == 0) costSecond = 1;
        return Math.round(results.size()*1.0 / costSecond);
    }

    public double tps(long uv) {
        double avg = avgCost();
        if (avg == 0) return 0;
        return Math.round(uv / (avgCost() / 1000.0));
    }

    /**
     * 响应时间中位数
     *
     * @return
     */
    public long midCost() {
        long[] costs = results.stream().filter(Objects::nonNull).mapToLong(Result::getCost).sorted().toArray();
        long midNumber;
        if (costs.length == 1) {
            midNumber = costs[0];
        } else if (costs.length % 2 == 0) {
            midNumber = (costs[costs.length / 2] + costs[costs.length / 2 - 1]) / 2;
        } else {
            midNumber = costs[costs.length / 2];
        }
        return midNumber;
    }

    /**
     * 响应时间平均值
     *
     * @return
     */
    public double avgCost() {
        long sum = results.stream().filter(Objects::nonNull).mapToLong(Result::getCost).sum();
        if (results.size() == 0) return 0;
        return sum*1.0 / results.size();
    }

    /**
     * 总数
     *
     * @return
     */
    public long count() {
        return results.size();
    }

    /**
     * 成功率
     *
     * @return
     */
    public double successRate() {
        long count = results.stream().filter(Objects::nonNull).filter(Result::isSuccess).count();
        return Math.round(count * 100.0 / results.size());
    }
}
